import {EventEmitter} from 'events'
import AppDispatcher from './AppDispatcher'
import * as ActionTypes from './ActionTypes'
import CounterStore from './CounterStore'


function computeSummary(counterValues){
    var summary = 0;
    for(const key in counterValues){
        if(counterValues.hasOwnProperty(key)){
            summary += counterValues[key];
        }

    }
    return summary;
}

const CHANGE_EVENT = "SummaryStoreChanged";

const SummaryStore = Object.assign({},EventEmitter.prototype,{
    getSummary:function(){
        return computeSummary(CounterStore.getCounterValues());
    },
    emitChange: function() {
        this.emit(CHANGE_EVENT);
    },

    addChangeListener: function(callback) {
        this.on(CHANGE_EVENT, callback);
    },

    removeChangeListener: function(callback) {
        this.removeListener(CHANGE_EVENT, callback);
    }
});

SummaryStore.dispatchToken = AppDispatcher.register((action)=>{
    if(action.type == ActionTypes.TYPE_INCREMENT || action.type == ActionTypes.TYPE_DECREMENT){
        AppDispatcher.waitFor([CounterStore.dispatchToken]);
        SummaryStore.emitChange();
    }
});

export default SummaryStore;